package com.base.demo;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

public class LockRedis {
    private JedisPool jedisPool;
    private String redislockKey = "redis_lock";

    public LockRedis(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    //redis 以key  和 value （不重复数据）进行存储。

    /**
     *
     * @param acquireTimeout 在获取锁前的超时时间
     * @param timeout 获取锁后的超时时间
     */
    public String getRedisLock(Long acquireTimeout, Long timeout) {

        Jedis conn = null;
        try {
            conn = jedisPool.getResource();
            String value = UUID.randomUUID().toString();
            int expireLock = (int) (timeout / 1000);
            Long endTime = System.currentTimeMillis() + acquireTimeout;
            while (System.currentTimeMillis() < endTime ) {
                if(conn.setnx(redislockKey, value) == 1) {
                    conn.expire(redislockKey,expireLock);
                    return value;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (conn != null) {
               conn.close();
            }
        }
        return null;
    }

    public void unRedisLock(String value) {
        Jedis conn = null;
        conn = jedisPool.getResource();
        try {
            if(conn.get(redislockKey).equals(value)) {  //要加上这个判断，确保自己的锁自己删除
                System.out.println(Thread.currentThread().getName() + "释放锁");
                conn.del(redislockKey);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(conn != null) {
                conn.close();
            }
        }
    }
}
